package cn.akwangl.socket.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Slf4j
public class NIOBufferCopy implements FileCopy {
    @Override
    public void copyFile(File source, File target) {
        CreateTestData.fileInit(target, true);

        FileChannel fin = null;
        FileChannel fos = null;
        try {
            fin = new FileInputStream(source).getChannel();
            fos = new FileOutputStream(target).getChannel();

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            while (fin.read(byteBuffer) != -1) {
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()) {
                    fos.write(byteBuffer);
                }
                byteBuffer.clear();
            }
        } catch (FileNotFoundException e) {
            log.error("找不到文件", e);
        } catch (IOException e) {
            log.error("IO 异常", e);
        } finally {
            try {
                fin.close();
                fos.close();
            } catch (IOException e) {
                log.error("释放资源失败", e);
            }
        }
    }
}
